package com.promise.jokerdream.ui.components

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.TextRange
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.foundation.layout.FlowRow
import com.promise.jokerdream.ui.theme.AppSpacing
import com.promise.jokerdream.ui.theme.AppColors
import com.promise.jokerdream.ui.theme.AppFontSizes
import androidx.compose.runtime.rememberCompositionContext
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.SoftwareKeyboardController

/**
 * 单选Hashtag输入半浮层
 */
@Composable
fun SingleSelectHashtagBottomSheet(
    modifier: Modifier = Modifier,
    title: String = "选择标签",
    initialText: String = "",
    placeholder: String = "输入或选择标签",
    recommendedTags: List<String> = emptyList(),
    onCancel: () -> Unit,
    onComplete: (String) -> Unit,
    onDismiss: (() -> Unit)? = null
) {
    val compositionContext = rememberCompositionContext()
    
    // 创建 PMBottomSheetDialog
    val pmDialog = pmBottomSheetDialog(onDismiss = onDismiss)
    
    // 设置 Compose 内容
    pmDialog.setContent(compositionContext) {
        MaterialTheme {
            BottomSheetContent(
                title = title,
                initialText = initialText,
                placeholder = placeholder,
                recommendedTags = recommendedTags,
                onCancel = {
                    pmDialog.dismiss()
                    onCancel()
                },
                onComplete = { text ->
                    pmDialog.dismiss()
                    onComplete(text)
                }
            )
        }
    }
    
    // 显示对话框
    LaunchedEffect(Unit) {
        pmDialog.show()
    }

    // 清理资源
    DisposableEffect(Unit) {
        onDispose {
            pmDialog.dismiss()
        }
    }
}


/**
 * BottomSheet 的 Compose 内容
 */
@Composable
private fun BottomSheetContent(
    title: String,
    initialText: String,
    placeholder: String,
    recommendedTags: List<String>,
    onCancel: () -> Unit,
    onComplete: (String) -> Unit
) {
    var inputText by remember { mutableStateOf(initialText) }
    val focusRequester = remember { FocusRequester() }
    val keyboardController = LocalSoftwareKeyboardController.current
    val configuration = LocalConfiguration.current
    val screenHeight = configuration.screenHeightDp
    val height = with(screenHeight) {
        (screenHeight * 0.75).toInt().dp
    }


    Column(
        modifier = Modifier
            .fillMaxWidth()
            .height(height)
            .padding(vertical = AppSpacing.pageVertical)
            .padding(horizontal = AppSpacing.pageHorizontal)
            .verticalScroll(rememberScrollState())
    ) {
        // 顶部标题栏
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 取消按钮 - 左端
            Text(
                text = "取消",
                fontSize = AppFontSizes.body,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier.clickable { onCancel() }
            )

            // 标题 - 居中
            Text(
                text = title,
                fontSize = AppFontSizes.h4,
                fontWeight = FontWeight.SemiBold,
                color = MaterialTheme.colorScheme.onSurface,
                textAlign = TextAlign.Center,
                modifier = Modifier.weight(1f)
            )

            // 完成按钮 - 右端
            Text(
                text = "完成",
                fontSize = AppFontSizes.body,
                color = if (inputText.isNotEmpty())
                    MaterialTheme.colorScheme.primary
                else MaterialTheme.colorScheme.onSurfaceVariant,
                fontWeight = FontWeight.Medium,
                modifier = Modifier.clickable(enabled = inputText.isNotEmpty()) { 
                    onComplete(inputText) 
                }
            )
        }

        // 输入框 - 只有当initialText不为空时才显示
        if (initialText.isNotEmpty()) {
            Spacer(modifier = Modifier.height(AppSpacing.componentLarge))

            SingleSelectInputField(
                text = inputText,
                placeholder = placeholder,
                onTextChange = { inputText = it },
                focusRequester = focusRequester,
                keyboardController = keyboardController
            )

            Spacer(modifier = Modifier.height(AppSpacing.componentLarge))
        } else {
            // 没有输入框时添加小的间距
            Spacer(modifier = Modifier.height(AppSpacing.componentMedium))
        }

        // 推荐部分
        if (recommendedTags.isNotEmpty()) {
            Text(
                text = "推荐",
                fontSize = AppFontSizes.mediumBody,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier.padding(bottom = AppSpacing.componentSmall)
            )

            // 推荐标签列表
            SingleSelectTagsList(
                tags = recommendedTags,
                selectedTag = inputText,
                onTagClick = { tag ->
                    inputText = tag
                }
            )
        }
    }
}

/**
 * 单选输入框
 */
@Composable
private fun SingleSelectInputField(
    text: String,
    placeholder: String,
    onTextChange: (String) -> Unit,
    focusRequester: FocusRequester,
    keyboardController: SoftwareKeyboardController?
) {
    var textFieldValue by remember(text) {
        mutableStateOf(TextFieldValue(text, TextRange(text.length))) 
    }

    BasicTextField(
        value = textFieldValue,
        onValueChange = { newValue ->
            textFieldValue = newValue
            onTextChange(newValue.text)
        },
        modifier = Modifier
            .fillMaxWidth()
            .focusRequester(focusRequester)
            .clip(RoundedCornerShape(AppSpacing.componentSmall))
            .background(AppColors.InputFieldBackground)
            .padding(AppSpacing.componentMedium),
        textStyle = TextStyle(
            fontSize = AppFontSizes.body,
            color = MaterialTheme.colorScheme.onSurface
        ),
        cursorBrush = SolidColor(MaterialTheme.colorScheme.primary),
        keyboardOptions = KeyboardOptions(
            capitalization = KeyboardCapitalization.None,
            imeAction = ImeAction.Done
        ),
        keyboardActions = KeyboardActions(
            onDone = { keyboardController?.hide() }
        ),
        decorationBox = { innerTextField ->
            if (textFieldValue.text.isEmpty()) {
                Text(
                    text = placeholder,
                    fontSize = AppFontSizes.mediumBody,
                    lineHeight = 16.sp,
                    color = AppColors.InputFieldPlaceholder
                )
            }
            innerTextField()
        }
    )
}

/**
 * 单选推荐标签列表（流式布局）
 */
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun SingleSelectTagsList(
    tags: List<String>,
    selectedTag: String,
    onTagClick: (String) -> Unit
) {
    FlowRow(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(AppSpacing.componentMedium),
        verticalArrangement = Arrangement.spacedBy(AppSpacing.componentMedium) // 设置合理的行间距
    ) {
        tags.forEach { tag ->
            SingleSelectTagChip(
                text = tag,
                isSelected = selectedTag == tag,
                onClick = { onTagClick(tag) }
            )
        }
    }
}

/**
 * 单选标签芯片
 */
@Composable
private fun SingleSelectTagChip(
    text: String,
    isSelected: Boolean,
    onClick: () -> Unit
) {
    Box(
        modifier = Modifier
            .clickable(
                interactionSource = remember { MutableInteractionSource() },
                indication = null
            ) { onClick() }
            .clip(RoundedCornerShape(8.dp))
            .background(
                if (isSelected) 
                    AppColors.Selected.copy(alpha = 0.12f) // 选中背景色
                else AppColors.Gray100 // 未选中背景色
            )
    ) {
        Text(
            text = text,
            fontSize = AppFontSizes.mediumBody,
            color = if (isSelected) 
                AppColors.Selected // 选中文案颜色
            else AppColors.TextSecondary, // 未选中文案颜色
            modifier = Modifier.padding(
                horizontal = AppSpacing.componentMedium,
                vertical = AppSpacing.componentSmall
            )
        )
    }
}
